package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.ann.Log;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.*;

@Service

public class EmpServiceImpl implements EmpService {

    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;


    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
//defaultValue 设置默认值
//    public PageResult<Emp> page(@RequestParam(defaultValue = "1") Integer page,
//                                @RequestParam(defaultValue = "10") Integer pageSize) {
//        Long count = empMapper.count();
//       Integer start= (page - 1) * pageSize;
//        List<Emp> empList = empMapper.list(start, pageSize);
//        return new PageResult<>(count, empList);
//    }

    /**
     * PageHelper方法分页查询
     * @param empQueryParam
     * @return
     * 注意事项：
     *      1.定义的SQL语句结尾不能加分号
     *      2.PageHelper仅仅能对跟在其后面的第一个查询语句进行处理
     */
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());


        Page<Emp> page= empMapper.queryPage(empQueryParam);
         return new PageResult<>(page.getTotal(),page.getResult());
    }

   /**
     * 新增员工
     * @param emp
     */
   @Log
   @Transactional(rollbackFor={Exception.class}) //事务管理--默认出现运行时异常RunTimeException才会回滚
    public void save(Emp emp) {
       try {
           emp.setCreateTime(LocalDateTime.now());
           emp.setUpdateTime(LocalDateTime.now());
           empMapper.insert(emp);
           List<EmpExpr> exprList = emp.getExprList();
           if (!CollectionUtils.isEmpty(exprList)){
               for (EmpExpr expr : exprList) {
                   expr.setEmpId(emp.getId());
               }
                   empExprMapper.insertBatch(exprList);
            }
       } finally {
           EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "新增员工：" + emp);
           empLogService.insertLog(empLog);
       }

   }

    /**
     * 批量删除员工
     * @param ids
     */
    @Log
    @Transactional(rollbackFor={Exception.class})
    public void deleteBatch(List<Integer> ids) {

        empMapper.deleteById(ids);

        empExprMapper.deleteByEmpId(ids);

    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    public Emp getById(Integer id) {
        Emp emp = empMapper.getById(id);
        return emp;
    }

    /**
     * 修改员工信息
     * @param emp
     */
    @Log
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)){
            empExprMapper.deleteByEmpId(Arrays.asList(emp.getId()));
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprMapper.insertBatch(exprList);
        }
    }

    /**
     * 员工登录
     * @param emp
     * @return
     */
    public LoginInfo login(Emp emp) {
        Emp empsels=empMapper.querySelect(emp);
        if (empsels!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",empsels.getId());
            claims.put("username",empsels.getUsername());
            String token = JWTUtils.createToken(claims);
            return new LoginInfo(empsels.getId(), empsels.getUsername(), empsels.getName(), token);
        }
        return null;
    }

    /**
     * 查询所有员工
     * @return
     */
    public List<Emp> list() {
        return empMapper.list();
    }
}
